package pt.utl.ist.project_ccu;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import pt.utl.ist.project_ccu.android_libs.Album;
import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.SavedData;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
 
public class AlbumViewer extends Activity {
    /** Called when the activity is first created. */
	private Map<Integer, Album> _albuns = new TreeMap<Integer,Album>();
	private Activity thisActivity;
	private AlertDialog _alertDialog;
	private Album _allPhotos;
	private Album _untaggedPhotos;
	private GridView gridView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        thisActivity = this;
        SavedData.getInstance().updateActivity(this);
        List<Album> albuns = SavedData.getInstance().getAlbuns();
        if(albuns == null) {
        	albuns = new ArrayList<Album>();
        }
        _allPhotos = new Album("AllPhotos");
        _untaggedPhotos = new Album("UntaggedPhotos");
        _allPhotos.addPhotos(SavedData.getInstance().getAllPhotos());
        _untaggedPhotos.addPhotos(SavedData.getInstance().getUntaggedPhotos());
        _albuns.put(0,_allPhotos);
        _albuns.put(1,_untaggedPhotos);
        
        
        int i = 2;
        for (Album al : albuns) {
        	_albuns.put(i,al);
        	++i;
        }
        setContentView(R.layout.grid_layout_album);
        gridView = (GridView) findViewById(R.id.grid_view);
        gridView.setAdapter(new ImageAdapter(this));


        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            	
            }
        });
        

    }
    
    @Override
    public void onResume() 
    { 
        super.onResume();
        resetDefaultAlbuns();
  
    }
    
    @Override
    public void onStart() 
    { 
        super.onStart(); 
        resetDefaultAlbuns();
  
    }
    
    public void resetDefaultAlbuns() {
        _allPhotos = new Album("AllPhotos");
        _untaggedPhotos = new Album("UntaggedPhotos");
        _albuns.put(0,_allPhotos);
        _albuns.put(1,_untaggedPhotos);
        _allPhotos.addPhotos(SavedData.getInstance().getAllPhotos());
        _untaggedPhotos.addPhotos(SavedData.getInstance().getUntaggedPhotos());
    }
    
	private TextView createDialogTitle(String titleText) {
		TextView title = new TextView(this);
		// You Can Customise your Title here 
		title.setText(titleText);
		title.setBackgroundColor(Color.DKGRAY);
		title.setPadding(10, 10, 10, 10);
		title.setGravity(Gravity.CENTER);
		title.setTextColor(Color.WHITE);
		title.setTextSize(20);
		return title;
	}
	
	private TextView createDialogTitle() {
		TextView title = new TextView(this);
		// You Can Customise your Title here 
		title.setText("Album Options");
		title.setBackgroundColor(Color.DKGRAY);
		title.setPadding(10, 10, 10, 10);
		title.setGravity(Gravity.CENTER);
		title.setTextColor(Color.WHITE);
		title.setTextSize(20);
		return title;
	}
	
	private void showDialog(Context context, final Album album) {
        if( _alertDialog != null && _alertDialog.isShowing() ) return;
        TextView title = createDialogTitle();
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCustomTitle(title);
        builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		SavedData.getInstance().removeAlbum(album);
        		gridView.invalidateViews();
        	}});
        builder.setNeutralButton("Rename", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		popWindow(album);
        		dialog.dismiss();
        	}});

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int arg1) {
        		dialog.dismiss();
        	}});
        builder.setCancelable(true);
        _alertDialog = builder.create();
        try {
        	_alertDialog.show();
        }
        catch(Exception e) {}
	}
	
	public void  popWindow(final Album album) {

		// get prompts.xml view
		LayoutInflater li = LayoutInflater.from(thisActivity);
		View promptsView = li.inflate(R.layout.rename_prompt, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				thisActivity);

		// set prompts.xml to alertdialog builder
		alertDialogBuilder.setView(promptsView);

		final EditText userInput = (EditText) promptsView
				.findViewById(R.id.editTextDialogUserInput);

		// set dialog message
		alertDialogBuilder
		.setCancelable(false)
		.setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				album.setName(userInput.getText().toString());
				gridView.invalidateViews();
			}
		})
		.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		try {
			alertDialog.show();
		}
		catch(Exception e) {}
	}
	
	private void showDialogForPredefinedAlbum(Context context) {
        if( _alertDialog != null && _alertDialog.isShowing() ) return;

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCustomTitle(createDialogTitle("Album Options"));
        builder.setMessage("Can't alter predefined Albuns");
        builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
            }});
        builder.setCancelable(true);
        _alertDialog = builder.create();
        try {
        	_alertDialog.show();
        }
        catch(Exception e) {}
	}

 
	public class ImageAdapter extends BaseAdapter {
	    int mGalleryItemBackground;
	    private Context mContext;
	    private LayoutInflater mInflater;
	 
	    public ImageAdapter(Context c) {
	        mContext = c;
	        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    }
	 
	    public int getCount() {
	        return _albuns.size();
	    }
	 
	    public Object getItem(int position) {
	        return position;
	    }
	 
	    public long getItemId(int position) {
	        return position;
	    }
	 
	    public View getView(int position, View convertView, ViewGroup parent) {
	    	ViewHolder holder;
	    	if(convertView == null) {
	    		holder = new ViewHolder();
	    		convertView = mInflater.inflate(R.layout.albumitem, null);
	    		holder.imageview = (ImageView) convertView.findViewById(R.id.albumView);
	    		holder.textBox = (TextView) convertView.findViewById(R.id.albumName);
	    		holder.album = _albuns.get(position);
	    		holder.textBox.setText(holder.album.getAlbumName());
	    		holder.textBox.setTextSize(11);
	    		convertView.setTag(holder);
	    	}
	    	else {
	    		holder = (ViewHolder) convertView.getTag();
	    	}
	    	
	    	holder.imageview.setId(position);
	    	final int pos = position;
	    	final String albumName = holder.album.getAlbumName();
	    	
	    	holder.imageview.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					Intent intent = new Intent(getApplicationContext(),PhoPhotoViewer.class);
					ArrayList<Photo> photos = _albuns.get(pos).getPhotos();
					intent.putExtra("photos", photos);
					startActivityForResult(intent,0);
					
				}
	    		
	    	});
	    	
	    	holder.imageview.setOnLongClickListener(new OnLongClickListener() {

				public boolean onLongClick(View v) {
					Album album = _albuns.get(pos);
					String albumName = album.getAlbumName();
					if(albumName.equals("AllPhotos") || albumName.equals("UntaggedPhotos")) {
						showDialogForPredefinedAlbum(thisActivity);
					}
					else {
						showDialog(thisActivity, _albuns.get(pos));
					}
					return true;
					
				}
	    		
	    	});
	    	
			holder.id = position;
			return convertView;
	    }
	    

 
	}
	
	class ViewHolder {
		Album album;
		ImageView imageview;
		TextView textBox;
		int id;
	}
}

